import { HttpCode, Injectable } from '@nestjs/common';
import { CreateBossDto } from './dto/create-boss.dto';
import { UpdateBossDto, updatePriceBossDto } from './dto/update-boss.dto';
import { ILike, Like, Repository } from 'typeorm';
import { Boss } from './entities/boss.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { uid } from 'uid'
import { loadPageQueryResult } from 'src/utils/utils';
@Injectable()


export class BossService {
  constructor(
    @InjectRepository(Boss) private readonly bossRepository: Repository<Boss>,
  ) { }

  //添加
  async create(createBossDto: CreateBossDto) {
    await this.bossRepository.save({ ...createBossDto, bossId: uid() });
    return {
      code: 1,
      message: '添加成功'
    };
  }
  //分页查询
  async findAll(pageNum?: number, pageSize?: number, bossName?: string) {

    let res = await this.bossRepository.findAndCount({
      where: {
        bossName: bossName ? ILike(`%${bossName}%`) : undefined
      },
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
      order: { id: 'DESC' }
    })

    return {
      code: 1,
      data: loadPageQueryResult<[Boss[], number]>(res, pageNum, pageSize)
    };
  }
  //详情
  async findOne(bossId: string) {
    let data = await this.bossRepository.findOne({
      where: { bossId }
    })
    return {
      code: 1,
      data
    };
  }
  //更新
  async update(bossId: string, bossName: string) {
    await this.bossRepository.update({ bossId }, { bossName });
    return {
      code: 1,
      message: "更新成功"
    };
  }
  //删除
  async remove(bossId: string) {
    await this.bossRepository.delete({ bossId });
    return {
      code: 1,
      message: "删除成功"
    };
  }
  //存单
  async updatePrice(updatePriceBossDto: updatePriceBossDto) {
    console.log(updatePriceBossDto.bossId)
    //查询
    let current = await this.bossRepository.findOne({
      select: ['amount'],
      where: {
        bossId: updatePriceBossDto.bossId
      }
    })
    console.log(current)
    let amount = current.amount + updatePriceBossDto.amount;
    console.log(amount, current.amount, updatePriceBossDto.amount)
    await this.bossRepository.update({ bossId: updatePriceBossDto.bossId }, { amount });
    return {
      code: 1,
      message: "存单成功"
    };
  }
}
